package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.eims.sls_app.dataaccess.Users;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.MyPushTask;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.view.MyToast;

import org.json.JSONObject;

import java.lang.reflect.Method;

import bls.juejin.cn.R;

/**
 * 功能：用户登录界面，实现登录
 */
public class NewLoginActivity extends MyBaseActivity implements OnClickListener {
    public static final int SHOW_MSG = 233;
    private EditText et_name, et_pass;
    private Button btn_login, btn_reg;
    private ImageView activity_login_check;
    private TextView activity_login_forgetpass;
    private String userName, userPass; // 获得用户输入的用户名 // 获得用户输入的密码
    private String opt, auth, info, time, imei; // 格式化后的参数
    private SharedPreferences settings;
    private ProgressDialog mProgress = null;
    private Intent intent;
    private String tagName = "loginTag";
    private String pass;
    private MyHandler myHandler;
    private ImageButton ivBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_new_login);
        App.activityS.add(this);
        findView();
        init();
        setListener();
    }

    /**
     * 判断用户是否登陆过
     */
    private void init() {
        settings = this.getSharedPreferences("app_user", 0);
        boolean isLogin = false;// 没有登录的标识
        String name = "";
        String pass = "";
        if (settings.contains("isLogin")) {
            isLogin = settings.getBoolean("isLogin", false);
        }
        if (settings.contains("name")) {
            name = settings.getString("name", null);
        }
        // 是否记录密码
        boolean isRecord = settings.getBoolean("isRecord", false);

        if (isRecord) {
            et_pass.setText(settings.getString("pass", null));
        }
        activity_login_check.setSelected(isRecord);
        // 显示下划线
        activity_login_forgetpass.getPaint()
                .setFlags(Paint.UNDERLINE_TEXT_FLAG);
        // 判断是否有存 用户名
        if (isLogin) {
            // 判断是否有存 密码
            if (settings.contains("pass")) {
                pass = settings.getString("pass", null);
            }
            et_pass.setText(pass);
        }
        et_name.setText(name);
        et_name.setSelection(et_name.getText().length());
        if (null != pass && name != null && !"".equals(name)
                && !"".equals(pass) && isLogin) {
            String type = getIntent().getStringExtra("loginType");
            if (!"genggai".equals(type))
                doLogin();
        }
    }

    /**
     * 初始化
     */
    private void findView() {
        myHandler = new MyHandler();
        ivBack = (ImageButton) findViewById(R.id.btn_back);
        et_name = (EditText) this.findViewById(R.id.et_userName);
        et_pass = (EditText) this.findViewById(R.id.et_userPass);
        btn_login = (Button) this.findViewById(R.id.login_btn_login);
        btn_reg = (Button) this.findViewById(R.id.login_top_btn_reg);
        btn_reg.setText("还没有" + getResources().getString(R.string.app_logo)
                + "账号？立即注册");
        activity_login_check = (ImageView) this
                .findViewById(R.id.activity_login_check);
        activity_login_forgetpass = (TextView) this
                .findViewById(R.id.activity_login_forgetpass);
        time = RspBodyBaseBean.getTime();
        imei = RspBodyBaseBean.getIMEI(NewLoginActivity.this);
    }

    /**
     * 绑定监听
     */
    private void setListener() {
        btn_login.setOnClickListener(this);
        btn_reg.setOnClickListener(this);
        activity_login_check.setOnClickListener(this);
        activity_login_forgetpass.setOnClickListener(this);
        ivBack.setOnClickListener(this);

    }

    /* 设置键盘 软盘 */
    private void setting() {
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            et_name.setInputType(InputType.TYPE_NULL);
            et_pass.setInputType(InputType.TYPE_NULL); // 关闭软键盘
        } else {
            getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod(
                        "setSoftInputShownOnFocus", boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(et_name, false);
                setSoftInputShownOnFocus.invoke(et_pass, false);
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_name.getWindowToken(), 0);
                imm.hideSoftInputFromWindow(et_pass.getWindowToken(), 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 公共点击监听
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
//                finish();
                break;
            case R.id.login_btn_login:
                doLogin();
                break;
            case R.id.login_top_btn_reg:
                doRegister();
                break;
            case R.id.activity_login_forgetpass:// 忘记密码
                Intent intent1 = new Intent(this, ForgetPasswordActivity.class);
                startActivity(intent1);
                break;
            case R.id.activity_login_check:
                boolean isSelect = activity_login_check.isSelected();
                activity_login_check.setSelected(!isSelect);
                Editor editor = settings.edit();
                editor.putBoolean("isRecord", !isSelect);
                editor.commit();
                break;
        }
    }

    /**
     * 登录
     */
    private void doLogin() {
        userName = et_name.getText().toString().trim();
        userPass = et_pass.getText().toString().trim();
        if (userName.length() == 0) {
            MyToast.getToast(NewLoginActivity.this, "用户名不能为空").show();
            return;
        }
        if (userPass.length() == 0) {
            MyToast.getToast(NewLoginActivity.this, "密码不能为空").show();
            return;
        }

        if (NetWork.isConnect(NewLoginActivity.this)) {
            MyAsynTask myAsyn = new MyAsynTask();
            myAsyn.execute();
        } else {
            MyToast.getToast(NewLoginActivity.this, "网络异常,登陆失败").show();
        }
    }

    /**
     * 跳到注册页面
     */
    private void doRegister() {
        intent = new Intent(NewLoginActivity.this, RegisterNewActivity.class);
        NewLoginActivity.this.startActivity(intent);
//        NewLoginActivity.this.finish();
    }


    /**
     * 异步任务
     */
    class MyAsynTask extends AsyncTask<Void, Integer, String> {
        /**
         * 在后台执行的程序
         */
        @Override
        protected String doInBackground(Void... params) {
            // 对密码进行MD5加密
            pass = MD5.md5(userPass + App.MD5_key);
            opt = "2";
            info = RspBodyBaseBean.changeLogin_Info(userName, pass);
            auth = RspBodyBaseBean.changeLogin_Auth(
                    RspBodyBaseBean.getCrc(time, imei,
                            MD5.md5(App.MD5_key), info, "-1"), time, imei);
            String[] values = {opt, auth, info};
            Log.i("login", "登录info---" + info);
            String result = HttpUtils.doPost(App.names, values,
                    App.path);
            Log.e("login", "登录result---" + result);
            if ("-500".equals(result))
                return "-500";

            try {
                JSONObject item = new JSONObject(result);
                if ("0".equals(item.optString("error"))) {
                    App.user = new Users();
                    App.user.setUid(item.optString("uid"));
                    App.user.setName(item.optString("name"));
                    App.user.setRealityName(item.optString("realityName"));
                    App.user.setBalance(item.optDouble("balance"));
                    App.user.setFreeze(item.optDouble("freeze"));
                    App.user.setEmail(item.optString("email"));
                    App.user.setIdcardnumber(item
                            .optString("idcardnumber"));
                    App.user.setMobile(item.optString("mobile"));
                    App.user.setMsgCount(item.optInt("msgCount"));
                    App.user.setMsgCountAll(item.optInt("msgCountAll"));
                    App.user.setScoring(item.optInt("scoring"));
                    App.user.setHandselAmount(item
                            .optDouble("handselAmount"));
                    App.user.setHeadUrl(App.url + item.optString("headUrl"));
                    // 用户密码 （没加密的）
                    App.user.setUserPass(userPass);
                    App.user.setCode(item.optString("code"));
                    Log.e("code",item.optString("code"));

                    return App.ERROR_SUCCESS + "";
                } else {
                    // return item.optString("error");
                    return item.optString("msg");
                }
            } catch (Exception ex) {
                Log.i("login", "登录异常---" + ex.getMessage());
                return "-110";
            }
        }

        /**
         * 最开始执行的
         */
        @Override
        protected void onPreExecute() {
            mProgress = BaseHelper.showProgress(NewLoginActivity.this, null,
                    "登录中....", true, true);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO 这里要传递msg
            try {
                int error = Integer.parseInt(result);
                myHandler.sendEmptyMessage(error);
            } catch (Exception e) {
                myHandler.obtainMessage(SHOW_MSG, result).sendToTarget();
            }
            // myHandler.sendEmptyMessage(Integer.parseInt(result));
            super.onPostExecute(result);
        }
    }

//    /**
//     * 重写返回键事件
//     */
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            String str = getIntent().getStringExtra("loginType");
//            //if (str == null) {
//
//            Intent intent = new Intent(NewLoginActivity.this,
//                    MainActivity.class);
//
//            NewLoginActivity.this.startActivity(intent);
//            this.finish();
//
//
//            //MainActivity.toHall();
//
//
//            //}
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    /**
     * 处理页面显示的
     */
    @SuppressLint("HandlerLeak")
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
            switch (msg.what) {
                case 0:
                    if (App.user != null) {
                        App.Status = "1";
                        MyPushTask.newInstances(NewLoginActivity.this).commit();
                        String str = getIntent().getStringExtra("loginType");
                        if (str == null) {
                            // MainActivity.transaction.replace(R.id.main_center,new
                            // MyCenterFragment(), "center");
                            // MainActivity.transaction.commitAllowingStateLoss();

//                            MainActivity.toCenter();
                            Intent intent = new Intent(NewLoginActivity.this, MainActivity.class);
                            startActivity(intent);
//                            finish();

                        }

                        // 将用户名记住
                        settings = getSharedPreferences("app_user", 0);
                        Editor editor = settings.edit();
                        editor.putString("name", userName);
                        editor.putString("pass", userPass);

                        editor.putString("uid", App.user.getUid());
                        editor.putBoolean("isLogin", true);
                        editor.commit();
                        MyToast.getToast(NewLoginActivity.this, "登录成功").show();
                        // 登录成功 关闭Activity
                        NewLoginActivity.this.finish();
                    }
                    break;
                case -1:
                    MyToast.getToast(NewLoginActivity.this, "登录失败").show();
                    break;
                case -110:
                    MyToast.getToast(NewLoginActivity.this, "登录失败").show();
                    break;
                case -500:
                    MyToast.getToast(NewLoginActivity.this, "连接超时").show();
                    break;
                case -113:
                    MyToast.getToast(NewLoginActivity.this, "用户密码错误").show();
                    break;
                case -112:
                    MyToast.getToast(NewLoginActivity.this, "用户名不存在").show();
                    break;
                case SHOW_MSG:
                    String msgStr = (String) msg.obj;
                    MyToast.getToast(NewLoginActivity.this, msgStr).show();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        super.onNewIntent(intent);
    }

}
